/* eslint-disable */
import React from 'react'
import { withStyles } from '@material-ui/core/styles'
import PropTypes from 'prop-types'
import { inject, observer } from 'mobx-react'
import {
  Redirect,
} from 'react-router-dom'
import queryString from 'query-string'

import TextField from '@material-ui/core/TextField'
import Button from '@material-ui/core/Button'

import loginStyles from './styles/login-style'
import UserContainer from './user-container'

@inject((stores) => {
  return {
    appState: stores.appState,
    user: stores.appState.user,
  }
}) @observer
class UserLogin extends React.Component {
  constructor() {
    super()
    this.state = {
      accesstoken: '',
      helpText: '',
    }

    this.handleInput = this.handleInput.bind(this)
    this.handleLogin = this.handleLogin.bind(this)
    this.getFrom = this.getFrom.bind(this)
  }

  componentDidMount() {
    if (this.props.user.isLogin) {
      this.props.history.replace('/user/info')
    }
  }

  getFrom() {
    const from = queryString.parse(this.props.location.search).from
    return from || '/user/info'
  }

  handleInput(event) {
    const accessToken = event.target.value.trim()
    this.setState({
      accessToken: accessToken,
    })
  }

  handleLogin() {
    console.log("我们的accessToken是：", this.state.accessToken)
    if (!this.state.accessToken) {
      this.setState({
        helpText: '必须填写',
      })
      return
    }
    this.setState({
      helpText: '',
    })
    this.props.appState.login(this.state.accessToken).catch(msg => {
      this.props.appState.notify({ message:msg })
    })
  }

  render() {
    const classes = this.props.classes
    const isLogin = this.props.user.isLogin
    const from = this.getFrom()

    if (isLogin) {
      return <Redirect to={from} />
    }

    return (
      <UserContainer>
        <div className={classes.root}>
          <TextField
            label="请输入Cnode AccessToken"
            placeholder="请输入Cnode AccessToken"
            required
            helperText={this.state.helpText}
            onChange={this.handleInput}
            className={classes.input}
          />
          <Button
            raised="true"
            color="primary"
            onClick={this.handleLogin}
            className={classes.loginButton}
          >
            登 录
          </Button>
        </div>
      </UserContainer>
    )
  }
}

UserLogin.wrappedComponent.propTypes = {
  appState: PropTypes.object.isRequired,
  user: PropTypes.object.isRequired,
}

UserLogin.propTypes = {
  classes: PropTypes.object.isRequired,
  history: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired,
}

export default withStyles(loginStyles)(UserLogin)
